import express from 'express'
import bodyParser from 'body-parser'
import { userTypes } from './modules/database.mjs'
import { getFloorTree } from './modules/floor-tree.mjs'
import { statisticsRooms } from './modules/statistics.mjs'
import { searchRooms } from './modules/search-rooms.mjs'
const app = express()
const port = 3389
app.use(bodyParser.json())
app.use('/api', (req, res) => {
  res.setHeader('Content-Type', 'application/json')
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Headers', '*')
  res.setHeader('Access-Control-Allow-Methods', '*')
  res.setHeader('Access-Control-Allow-Credentials', 'true')
  res.setHeader('Cache-Control', 'private')
  req.next()
})
const successData = (data) => {
  return JSON.stringify({
    status: 200,
    data
  })
}
const errorData = (err) => {
  return JSON.stringify({
    status: 1,
    err,
    msg: err,
    message: err,
    error: err
  })
}
app.get('/api/usertypes', (req, res) => {
  res.send(successData(userTypes))
})

app.post('/api/floors', (req, res) => {
  res.send(successData(getFloorTree(req.body?.type || 'student')))
})

app.post('/api/statisticsrooms', (req, res) => {
  res.send(successData(statisticsRooms(req.body?.type || 'student')))
})

app.post('/api/searchrooms', (req, res) => {
  res.send(successData(searchRooms(req.body || {})))
})

app.listen(port, () => {
  console.log(`express服务器已启动，端口：${port}`)
})
